import tim from '../../utils/tim/tim'
import { getTimUserId, jump, getStorage, getBarAndTitleHeight } from '../../utils/utils'
import request from '../../utils/request'
import api from '../../config/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 会话列表
    conversationList: [0],
    // 信号栏高度
    ...getBarAndTitleHeight(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // 登入后拉去会话列表
    this.getList()

    // 监听会话更新
    tim.connect((conversationList) => {
      this.setData({
        conversationList,
      })
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 移除会话监听
    tim.disconnect((conversationList) => {
      this.setData({
        conversationList,
      })
    })
  },
  // 获取会话列表
  async getList() {
    let conversationList = []
    if (getStorage('userId')) {
      const userId = getTimUserId(getStorage('userId'))
      const res = await request.get(api.isImUser, { userId })
      if (res?.data) {
        await tim.login()
        conversationList = await tim.getMessageList()
      }
    }
    this.setData({
      conversationList,
    })
  },
  // 跳转会话
  jumpChat(event) {
    jump('chat', {
      conversationID: event.currentTarget.id
    })
  },
})
